//
//  WriteViewController.m
//  WonderfulNotes
//
//  Created by 千锋 on 16/1/6.
//  Copyright © 2016年 andy. All rights reserved.
//

#import "WriteViewController.h"
#import <Masonry.h>
#import "MLSelectPhotoAssets.h"
#import "MLSelectPhotoPickerBrowserPhoto.h"
#import "MLSelectPhotoPickerAssetsViewController.h"
#import "PhotosViewController.h"
#import <UIImageView+WebCache.h>
#import "AppDelegate.h"

#import "BmobOperation.h"
#import <BmobSDK/BmobProFile.h>

//#import "iflyMSC/IFlyRecognizerView.h"
//#import "iflyMSC/IFlySpeechConstant.h"
//#import "iflyMSC/IFlySpeechUtility.h"

#import "iflyMSC/IFlyMSC.H"

#import "UIColor+LNHex.h"

#define image_tag 100

static const CGFloat ToolBarHeight = 44;

@interface WriteViewController ()<IFlyRecognizerViewDelegate>
{
    //界面识别语音
    IFlyRecognizerView *_iflyRecongizerView;
    NSMutableString *_resultTitleString;
    NSMutableString * _resultNoteString;
    UIView *_currentActiveTF;
    
}

@property(nonatomic,strong) UITextField * titleTF;
@property(nonatomic,strong) UITextView * noteTV;
@property(nonatomic,strong) UIScrollView * scrollView;
@property(nonatomic,strong) UIButton * ImgBtn;
@property(nonatomic,strong) UIButton * voiceBtn;



//相片数组
@property(nonatomic,strong) NSMutableArray * assets;
//相片在沙河的路径数组
@property(nonatomic,strong) NSMutableArray * imageArray;
//获取上传后的url地址
@property(nonatomic,strong) NSMutableArray * urlArray;

@end

@implementation WriteViewController

-(NSMutableArray *)imageArray{
    
    if (_imageArray==nil) {
        
        _imageArray = @[].mutableCopy;
    }
    
    return _imageArray;
    
}

-(NSMutableArray *)urlArray{
    
    if (_urlArray==nil) {
        
        _urlArray = @[].mutableCopy;
    }
    return _urlArray;
}

-(NSMutableArray *)assets
{
    if (!_assets) {
        
        _assets = @[].mutableCopy;
    }
    
    return _assets;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createView];
    [self createNaviBarItem];
    [self setupVoiceRecongizerView];
    
   
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createView{
    
    self.titleTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH*3/4, ToolBarHeight)];
    [self.view addSubview:self.titleTF];
    if (self.noteTitle) {
            self.titleTF.text =self.noteTitle;
    }
    self.titleTF.placeholder = @"标题";
    self.titleTF.textColor = [UIColor grayColor];
    
    self.ImgBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.titleTF.frame)+10, 65, ToolBarHeight, ToolBarHeight)];
    [self.view addSubview:self.ImgBtn];
    self.ImgBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.ImgBtn setImage:[UIImage imageNamed:@"album"] forState:UIControlStateNormal];
    [self.ImgBtn addTarget:self action:@selector(pickerImageClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake((CGRectGetMinX(self.titleTF.frame)+20), CGRectGetMaxY(self.titleTF.frame)-10, SCREEN_WIDTH*3/4-40, 1)];
    [self.view addSubview:lineView];
    lineView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    
    self.noteTV = [[UITextView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.titleTF.frame), CGRectGetMaxY(lineView.frame)+5, SCREEN_WIDTH, (SCREEN_HEIGHT-110)/3)];
    [self.view addSubview:self.noteTV];
    self.noteTV.text = @"笔记内容";
    if (self.noteText) {
            self.noteTV.text = self.noteText;
        }else{
           self.noteTV.text = @"记得什么....";
    }
    self.noteTV.font = [UIFont systemFontOfSize:16];
    self.noteTV.textColor = [UIColor grayColor];
    self.noteTV.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.noteTV.hidden = NO;
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.noteTV.frame), CGRectGetMaxY(self.noteTV.frame)+2, SCREEN_WIDTH, (SCREEN_HEIGHT-110)/3)];
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = [UIColor grayColor];
        if (self.noteImage) {
    
            [self showImg];
        }
    
    self.voiceBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMidX(self.view.frame)-(SCREEN_HEIGHT-110)/12, CGRectGetMaxY(self.view.frame)-(SCREEN_HEIGHT-110)/6-10, (SCREEN_HEIGHT-110)/6, (SCREEN_HEIGHT-110)/6)];
    [self.view addSubview:self.voiceBtn];
    self.voiceBtn.layer.cornerRadius = (SCREEN_HEIGHT-110)/12;
    [self.voiceBtn setImage:[UIImage imageNamed:@"tabbar_compose_voice"] forState:UIControlStateNormal];
    [self.voiceBtn addTarget:self action:@selector(voiceBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)createNaviBarItem{
    
    //左边按钮
    
    if (self.index!=2) {
       
        UIBarButtonItem * leftBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(backClick)];
        self.navigationItem.leftBarButtonItem = leftBtn;
    }
    
    //右边按钮
    UIBarButtonItem * shareBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_icon_radar"] style:UIBarButtonItemStyleDone target:self action:@selector(shareClick)];
    
    UIBarButtonItem * saveBtn = [[UIBarButtonItem alloc]
                                 initWithTitle:@"保存"
                                 style:UIBarButtonItemStyleDone
                                 target:self
                                 action:@selector(saveClick)];
    
    NSArray * arr = @[shareBtn,saveBtn];
    self.navigationItem.rightBarButtonItems =arr;
    
    //自定义键盘的两个按钮
    UIBarButtonItem * doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(hideKeyboard)];
    doneBtn.width = ceilf(SCREEN_WIDTH)/3-30;
    
    UIBarButtonItem * voiceBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"voice"] style:UIBarButtonItemStylePlain target:self action:@selector(userVoiceINput)];
    voiceBtn.width = ceilf(SCREEN_WIDTH)/2-50;
    
    UIToolbar * toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ToolBarHeight)];
    toolBar.tintColor = [UIColor systemColor];
    toolBar.items = [NSArray arrayWithObjects:doneBtn,voiceBtn, nil];
    
    self.titleTF.inputAccessoryView = toolBar;
    self.noteTV.inputAccessoryView = toolBar;
    
}

-(void)backClick{
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - 语音录入1

-(void)voiceBtnClicked:(UIButton *)sender{
    
    //开始识别语音
    _currentActiveTF = self.titleTF;
    
    [_iflyRecongizerView start];
    
}

#pragma mark -语音录入2

-(void)userVoiceINput{
    
    if ([self.titleTF isFirstResponder]) {
        
        _currentActiveTF = self.titleTF;
        
    }else if ([self.noteTV isFirstResponder]) {
        
        _currentActiveTF = self.noteTV;
    }
    
    [self hideKeyboard];
    
    [_iflyRecongizerView start];
    
}

#pragma mark -语音读取功能

-(void)setupVoiceRecongizerView{
    
    //语音识别界面弹出点
    _iflyRecongizerView = [[IFlyRecognizerView alloc]initWithCenter:self.view.center];
    _iflyRecongizerView.delegate = self;
    
    //公共参量，应用领域
    [_iflyRecongizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //数据返回的类型，默认为json
    [_iflyRecongizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    
    _resultTitleString = [NSMutableString string];
    _resultNoteString = [NSMutableString string];
    
}

#pragma mark -IFlyRecognizerViewDelegate->语音转换问文字

-(void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast{
    
    NSMutableString * result = [[NSMutableString alloc]init];
    NSDictionary * dic = [resultArray objectAtIndex:0];
    for (NSString * key in dic) {
        [result appendFormat:@"%@",key];
    }

    if (_currentActiveTF==self.titleTF) {
       [_resultTitleString appendString:result];
    }
    if (_currentActiveTF==self.noteTV) {
        [_resultNoteString appendString:result];
    }
    
    if (isLast && (_resultTitleString.length>0 | _resultNoteString.length>0)) {
        
        if (_currentActiveTF == self.titleTF) {
            self.titleTF.text = _resultTitleString;
        }else if (_currentActiveTF == self.noteTV) {
            self.noteTV.text = _resultNoteString;
        }

    }

}

-(void)onError:(IFlySpeechError *)error{
    
    NSLog(@"错误码:%d",[error errorCode]);
    NSLog(@"错误描述:%@",[error errorDesc]);
    NSLog(@"错误码类:%d",[error errorType]);
    
}

#pragma mark - 键盘隐藏

-(void)hideKeyboard{
   
    if ([self.titleTF isFirstResponder]) {
        [self.titleTF resignFirstResponder];
    }
    if ([self.noteTV isFirstResponder]) {
        [self.noteTV resignFirstResponder];
    }
  
}

#pragma mark - 右边导航按钮
-(void)saveClick{
    
    //上传标题和文本
    if (![self.titleTF.text isEqualToString:@""] && ![self.noteTV.text isEqualToString:@""]) {
        
        [SVProgressHUD showWithStatus:@"云端同步..." maskType:SVProgressHUDMaskTypeGradient];
    
       if ([self.imageArray isEqualToArray:@[].mutableCopy]) {
        
        [self uploadData];
        
       }else{

        [BmobProFile uploadFilesWithDatas:self.imageArray resultBlock:^(NSArray *filenameArray, NSArray *urlArray, NSArray *bmobFileArray, NSError *error) {
            
            if (error) {
                NSLog(@"error=%@",error);
            }else{
                for (BmobFile * bfa in bmobFileArray) {
                    [self.urlArray addObject:bfa.url];
                    NSLog(@"文件地址－－%@",bfa.url);
                }
                [self uploadData];
            }
            
        } progress:^(NSUInteger index, CGFloat progress) {
            
            
        }];
      }
    }else{
        
        [SVProgressHUD showWithStatus:@"标题和内容缺一不可"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
            [SVProgressHUD dismiss];
        
        });
       
        
    }
    
}

-(void)uploadData{

    [BmobOperation addNoteToNoteTable:@"Note" noteTitle:self.titleTF.text noteText:self.noteTV.text noteImageUrl:self.urlArray todo:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:UPLOAD_NOTICE object:nil];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });

                });

              }
        }];
}

-(void)shareClick{
    
    NSLog(@"分享");
    
}

#pragma mark - 相片选取

-(void)pickerImageClicked:(UIButton *)sender{
    
    //创建图片选取器
    MLSelectPhotoPickerViewController * pickerVC = [[MLSelectPhotoPickerViewController alloc]init];
    pickerVC.topShowPhotoPicker = YES;
    pickerVC.status = PickerViewShowStatusCameraRoll;
    pickerVC.maxCount = 10;
    [pickerVC showPickerVc:self];
    //防止循环引用
    __weak typeof(self) weakSelf = self;
    pickerVC.callBack = ^(NSArray *assets){
        [weakSelf.assets addObjectsFromArray:assets];
        [self photoChange:(NSArray *)assets];
        [self pickerImage];
    };
}

#pragma mark - 转为本地后在上传
-(void)photoChange:(NSArray *)assets{
    
    for (int i=0; i<assets.count; i++) {
        
        UIImage * image = [MLSelectPhotoPickerViewController getImageWithImageObj:assets[i]];
        NSData * data = UIImagePNGRepresentation(image);
        //上传文件的格式必须是这样才行
        NSDictionary * dic =@{@"filename":[NSString stringWithFormat:@"andy%d",arc4random() % 100000],@"data":data};
        [self.imageArray addObject:dic];
    }

}

-(void)pickerImage{
    
    CGSize size = self.scrollView.frame.size;
    
    self.scrollView.bounces = NO;
    
    self.scrollView.contentSize = CGSizeMake(size.width, (size.width/3+5)*(self.assets.count/3+1));
    for (int index=0; index<self.assets.count; index++) {
        
        CGFloat imageX = 5 +index%3*size.width/3;
        CGFloat imageY =10+index/3*size.width/3;
        
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(imageX, imageY, size.width/3-10, size.width/3-10)];
        //设置图片拉伸模式
        imgView.contentMode = UIViewContentModeScaleToFill;
        imgView.userInteractionEnabled = YES;
        imgView.tag = image_tag+index;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
        
        tapGesture.numberOfTapsRequired = 1;
        [imgView addGestureRecognizer:tapGesture];
        
        imgView.image = [MLSelectPhotoPickerViewController getImageWithImageObj:self.assets[index]];
        
        [self.scrollView addSubview:imgView];
    }
    
}


-(void)doTap:(UITapGestureRecognizer *)sender{
    
    //获取当前点击的视图
    UIImageView * imageview = (id)sender.view;
       
    PhotosViewController * photosVC = [[PhotosViewController alloc]init];
    photosVC.index =imageview.tag-image_tag;
    photosVC.assets = self.assets;
    
    [self.navigationController pushViewController:photosVC animated:NO];
    
}

-(void)showImg{
    
    CGSize size = self.scrollView.frame.size;
    //CGSize size = CGSizeMake(375, 186);
    
    self.scrollView.bounces = NO;
    self.scrollView.contentSize = CGSizeMake(size.width, (size.width/3+5)*(self.noteImage.count/3+1));
    for (int index=0; index<self.noteImage.count; index++) {
        
        CGFloat imageX = 5 +index%3*size.width/3;
        CGFloat imageY =10+index/3*size.width/3;
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(imageX, imageY, size.width/3-10, size.width/3-10)];
        //设置图片拉伸模式
        imgView.contentMode = UIViewContentModeScaleToFill;
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
        tapGesture.numberOfTapsRequired = 1;
        [imgView addGestureRecognizer:tapGesture];
        [imgView sd_setImageWithURL:self.noteImage[index]];
        
        [self.scrollView addSubview:imgView];
        
    }

    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
